package org.example.aop;

import com.alibaba.fastjson.JSON;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.example.util.JwtUtils;
import org.example.web.domain.OperateLog;
import org.example.web.mapper.OperateLogMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Date;

@Component
@Aspect
public class LogAspect {
    @Autowired
    private OperateLogMapper operateLogMapper;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private JwtUtils jwtUtils;


    @Around("@annotation(org.example.annotation.MyLog)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        String token = request.getHeader("token");
        String username = jwtUtils.parseJwt(token).get("username").toString();
        OperateLog  operateLog = new OperateLog();
        //1
        operateLog.setOperator(username);
        //2
        operateLog.setOperateTime(new Date());
        //3
        operateLog.setClassName(joinPoint.getTarget().getClass().getName());
        //4
        operateLog.setMethodName(joinPoint.getSignature().getName());
        //5
        operateLog.setArgs(Arrays.toString(joinPoint.getArgs()));
        long begin = System.currentTimeMillis();
        Object proceed = joinPoint.proceed();
        long end = System.currentTimeMillis();
        //6
        operateLog.setReturnValues(JSON.toJSONString(proceed));
        //7
        operateLog.setCostTime(end - begin);

        operateLogMapper.insert(operateLog);
        return proceed;
    }
}
